<template>
  <div v-if="updateAvailable" class="fixed bottom-4 right-4 bg-base-200 p-4 rounded-lg shadow-lg z-50">
    <div class="flex flex-col gap-2">
      <div class="flex items-center justify-between gap-4">
        <div>
          <h3 class="text-lg font-semibold">发现新版本</h3>
          <p class="text-sm opacity-75">{{ updateInfo?.version }}</p>
        </div>
        <button @click="installUpdate" class="btn btn-primary btn-sm" :disabled="isUpdating">
          <i class="ri-download-2-line mr-1"></i>
          {{ isUpdating ? '更新中...' : '立即更新' }}
        </button>
      </div>
      
      <div v-if="isUpdating" class="w-full">
        <div class="flex justify-between text-xs mb-1">
          <span>下载进度</span>
          <span>{{ Math.round(downloadProgress) }}%</span>
        </div>
        <progress class="progress progress-primary w-full" :value="downloadProgress" max="100"></progress>
        <p class="text-xs mt-1 opacity-75">{{ downloadStatus }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { check } from '@tauri-apps/plugin-updater'
import { relaunch } from '@tauri-apps/plugin-process'
import { message } from '@tauri-apps/plugin-dialog'

const updateAvailable = ref(false)
const updateInfo = ref<any>(null)
const isUpdating = ref(false)
const downloadProgress = ref(0)
const downloadStatus = ref('')

const formatBytes = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
}

const checkForUpdates = async () => {
  try {
    const update = await check()
    console.log(update)
    if (update) {
      updateAvailable.value = true
      updateInfo.value = {
        version: update.version,
        date: update.date,
        body: update.body
      }
    }
  } catch (error) {
    console.error('检查更新失败:', error)
  }
}

const installUpdate = async () => {
  try {
    isUpdating.value = true
    downloadProgress.value = 0
    const update = await check()
    if (update) {
      await message('更新将在下载完成后自动安装，应用将自动重启', {
        title: '准备更新'
      })

      let downloaded = 0
      let contentLength = 0

      await update.downloadAndInstall((event) => {
        switch (event.event) {
          case 'Started':
            contentLength = event.data.contentLength || 0
            downloadStatus.value = `准备下载: ${formatBytes(contentLength)}`
            console.log(`开始下载: ${contentLength} bytes`)
            break
          case 'Progress':
            downloaded += event.data.chunkLength || 0
            downloadProgress.value = contentLength > 0 ? (downloaded / contentLength) * 100 : 0
            downloadStatus.value = `已下载 ${formatBytes(downloaded)} / ${formatBytes(contentLength)}`
            console.log(`已下载: ${downloaded} / ${contentLength}`)
            break
          case 'Finished':
            downloadStatus.value = '下载完成，准备安装...'
            console.log('下载完成')
            break
        }
      })

      console.log('更新已安装')
      await relaunch()
    }
  } catch (error) {
    console.error('安装更新失败:', error)
    await message('更新安装失败，请稍后重试', {
      title: '更新失败'
    })
  } finally {
    isUpdating.value = false
    downloadProgress.value = 0
    downloadStatus.value = ''
  }
}

onMounted(async () => {
  // 初始检查更新
  await checkForUpdates()
  
  // 每6小时检查一次更新
  // setInterval(checkForUpdates, 6 * 60 * 60 * 1000)
})
</script> 